//
//  VantagesVC.m
//  easyTaxi
//
//  Created by ellenpage on 13-1-8.
//  Copyright (c) 2013年 ellenpage. All rights reserved.
//

#import "Constant.h"
#import "VantagesVC.h"
#import "SocketObject.h"
#import "GetPhoneInfo.h"
#import "XMLWriter.h"
#import "RequestCMD.h"
#import "PassValueClass.h"
#import "MBProgressHUD.h"
#import "EGOImageView.h"
#import "EGOImageButton.h"
#import <MessageUI/MessageUI.h>

NSInteger currentCoverInt;
NSInteger tmpInt;
bool isAddedSubView;

@interface VantagesVC ()<UIAlertViewDelegate,EGOImageViewDelegate,EGOImageButtonDelegate>

@property (retain, nonatomic) NSString *scoreStr;//积分

@property (weak, nonatomic) IBOutlet EGOImageButton *vantageBtn1;
@property (weak, nonatomic) IBOutlet EGOImageButton *vantageBtn2;
@property (weak, nonatomic) IBOutlet EGOImageButton *vantageBtn3;
@property (weak, nonatomic) IBOutlet EGOImageButton *vantageBtn4;
@property (weak, nonatomic) IBOutlet EGOImageButton *vantageBtn5;
@property (weak, nonatomic) IBOutlet EGOImageButton *vantageBtn6;
@property (weak, nonatomic) IBOutlet EGOImageButton *vantageBtn7;
@property (weak, nonatomic) IBOutlet EGOImageButton *vantageBtn8;

@property (assign, nonatomic) NSInteger rewordInt;

@property (strong, nonatomic) IBOutlet UIView *aboutMoreView;

@property (retain, nonatomic) NSArray *dataArray;

@property (weak, nonatomic) IBOutlet UILabel *scoreLbl;

@property (strong, nonatomic) NSTimer *timer;

@property (strong, nonatomic) IBOutlet UIView *detailView;
@property (weak, nonatomic) IBOutlet UIView *detailView_Small;

@property (weak, nonatomic) IBOutlet EGOImageView *rewordImgView;
@property (weak, nonatomic) IBOutlet UILabel *rewordLbl;

@property (assign, nonatomic) NSInteger nextShowTag;
@property (weak, nonatomic) IBOutlet UITextView *ruleTxtView;
@property (weak, nonatomic) IBOutlet UIScrollView *rewordScrollView;
@property (weak, nonatomic) IBOutlet UIButton *startBtn;
@property (weak, nonatomic) IBOutlet UIButton *goBackBtn;

- (IBAction)goBack;

- (void)initialData;//加载数据

- (IBAction)startALottery;

- (void)verifyThisLottory:(NSInteger)index requestID:(NSString *)requestid;//验证

- (IBAction)hideRewordView;

- (IBAction)showAboutView;
- (IBAction)hideAboutView;

@end

@implementation VantagesVC

#pragma mark - GoBack - 返回

- (IBAction)goBack
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - System Function - 系统函数

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{            
    [self  quaryLottary];//查询中奖列表
    [self initialLottoryView];
    
    [YouMengEvent YouMengEvent:kJiFen_YouMeng];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self  initialData];//加载数据
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload
{
    [self setVantageBtn1: nil];
    [self setVantageBtn2: nil];
    [self setVantageBtn3: nil];
    [self setVantageBtn4: nil];
    [self setVantageBtn5: nil];
    [self setVantageBtn6: nil];
    [self setVantageBtn7: nil];
    [self setVantageBtn8: nil];
    [self setScoreLbl:nil];
    [self setAboutMoreView:nil];
    [self setDetailView:nil];
    [self setDetailView_Small:nil];
    [self setRewordImgView:nil];
    [self setRewordLbl:nil];
    [self setRuleTxtView:nil];
    [self setRewordScrollView:nil];
    [self setStartBtn:nil];
    [self setGoBackBtn:nil];
    [super viewDidUnload];
}

#pragma mark - InitialData - 加载数据

- (void)initialData
{
    _dataArray = @[@kVantageBtn1,@kVantageBtn2,@kVantageBtn3,@kVantageBtn4,@kVantageBtn5,@kVantageBtn6,@kVantageBtn7,@kVantageBtn8];
    
    _scoreStr      = [PassValueClass sharedIntance].scoreStr;
    _scoreLbl.text = _scoreStr;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getLottaryArray) name:kGetLottoryArrary object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getLottaryResult) name:kGetLottoryResult object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getLottaryConfirm) name:kGetLottoryConfirm object:nil];
    
    [self.view addSubview:_aboutMoreView];
    _aboutMoreView.hidden = YES;
    
    _detailView.backgroundColor = [[UIColor darkTextColor] colorWithAlphaComponent:0.65];
    [_detailView_Small.layer setCornerRadius:10];
    [_detailView_Small.layer setBorderColor:[[UIColor whiteColor] CGColor]];//描边颜色
    [_detailView_Small.layer setBorderWidth:2.0];//描边粗细
    [self.view addSubview:_detailView];
    _detailView.hidden = YES;
    
    _rewordScrollView.contentSize = CGSizeMake(280, 200);
    
}

#pragma mark - StartALottery - 开始抽奖

- (IBAction)startALottery
{
    NSString *costStr = [PassValueClass sharedIntance].costStr;
    if ([costStr intValue] > [_scoreLbl.text intValue])
    {
        UIAlertView *confirmAlert = [[UIAlertView alloc] initWithTitle:@"对不起,您的积分过少,不能参与抽奖" message:@"请攒够10分再来吧~" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
        [confirmAlert show];
        return;
    }
    
    NSString *messageStr = [NSString stringWithFormat:@"本次抽奖消耗%@积分",costStr];
    
    UIAlertView *confirmAlert = [[UIAlertView alloc] initWithTitle:@"确认抽奖?" message:messageStr delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认抽奖", nil];
    confirmAlert.tag = kVantageConfirmTag;
    [confirmAlert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    int i = alertView.tag;
    switch (i) {
        case kVantageConfirmTag:
        {
            if (buttonIndex == 1)
            {
                [self startLottary];
            }
        }
            break;
            
        case kUserLottoryAgain://再次抽奖
        {
            if (buttonIndex == 1)
            {
                [self startLottary];
            }
        }
            break;
        default:
            break;
    }
}

#pragma mark - QuaryLottary - 请求抽奖列表

- (void)quaryLottary
{
    NSString *string    = [RequestCMD requestCMD:kQuaryLottary];
    NSMutableData *data = [RequestCMD getWantedData:string];
    [[SocketObject sharedInstance].gcdSocket writeData:data withTimeout:-1 tag:kQuaryLottary];//1072---查询中奖列表
}

- (void)getLottaryArray
{
    _scoreLbl.text = [PassValueClass sharedIntance].scoreStr;

    NSArray *ruleArray = [PassValueClass sharedIntance].ruleArray;
    
    NSString *ruleStr = @"";
    for (int i = 0; i < ruleArray.count; i++)
    {
        NSString *str = [ruleArray objectAtIndex:i];
        
        NSString *blankStr = @"\n";
        ruleStr = [ruleStr stringByAppendingFormat:@"%@%@",str,blankStr];
    }
    _ruleTxtView.text = ruleStr;
    
    NSArray *array = [NSArray arrayWithArray:[PassValueClass sharedIntance].rewordArray];
    for (int i = 0; i < array.count; i++)
    {
        NSDictionary *tmpDict = [array objectAtIndex:i];
        NSInteger tagValue = [[tmpDict objectForKey:kRewordIndex] integerValue] + 100 - 1;
        NSString *str      = [tmpDict objectForKey:kRewordName];
        NSString *type     = [tmpDict objectForKey:kRewordType];
        NSString *picUrl   = [tmpDict objectForKey:kRewordUrl];
        
        EGOImageButton *btn = (EGOImageButton *)[self.view viewWithTag:tagValue];
        btn.imageURL = [NSURL URLWithString:picUrl];
        
        if (!isAddedSubView)
        {
            UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"awardtxt_bg.png"]];
            imgView.frame = CGRectMake(0, 0, 70, 70);
            [btn addSubview:imgView];
        
            UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(4, 48, 62, 21)];
            lbl.tag = btn.tag + 200;
            lbl.textAlignment = UITextAlignmentCenter;
            lbl.backgroundColor = [UIColor clearColor];
            lbl.text = str;
            lbl.font = [UIFont systemFontOfSize:13];
            if ([type isEqualToString:@"1"]||[type isEqualToString:@"2"]||[type isEqualToString:@"3"])
            {
                lbl.textColor = [UIColor redColor];
            }
            else
            {
                lbl.textColor = [UIColor blackColor];
            }
            [btn addSubview:lbl];
        
            UIImageView *tmpImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 70, 70)];
            tmpImgView.tag = btn.tag + 100;
            tmpImgView.image = [UIImage imageNamed:@"award_cover.png"];
            tmpImgView.userInteractionEnabled = NO;
            [btn addSubview:tmpImgView];

            if (i == array.count - 1)
            {
                isAddedSubView = YES;
            }
        }
        else
        {
            UILabel *tmpLbl = (UILabel *)[self.view viewWithTag:btn.tag + 200];
            tmpLbl.text = str;
            if ([type isEqualToString:@"1"]||[type isEqualToString:@"2"]||[type isEqualToString:@"3"])
            {
                tmpLbl.textColor = [UIColor redColor];
            }
            else
            {
                tmpLbl.textColor = [UIColor blackColor];
            }
        }
    }
}

#pragma mark - StartLottary - 开始抽奖

- (void)startLottary
{
    NSString *costStr = [PassValueClass sharedIntance].costStr;
    if ([costStr intValue] > [_scoreLbl.text intValue])
    {
        UIAlertView *confirmAlert = [[UIAlertView alloc] initWithTitle:@"对不起,您的积分过少,不能参与抽奖" message:@"请攒够10分再来吧~" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
        [confirmAlert show];
        return;
    }

    _startBtn.userInteractionEnabled = NO;
    _goBackBtn.userInteractionEnabled = NO;
    //--------------------1072---查询中奖结果
    NSString *string    = [RequestCMD requestCMD:kStartLottary];
    NSMutableData *data = [RequestCMD getWantedData:string];
    [[SocketObject sharedInstance].gcdSocket writeData:data withTimeout:-1 tag:kStartLottary];//1074---查询中奖列表
}

- (void)getLottaryResult
{
    [self initialLottoryView];//初始化抽奖数据
    
    NSDictionary *dict = [NSDictionary dictionaryWithDictionary:[PassValueClass sharedIntance].lottoryResultDict];
    NSString *index  = [dict objectForKey:kRewordIndex];
    
    _rewordInt = [index intValue] + 16 - currentCoverInt;
    if (currentCoverInt == 1)
    {
        UIImageView *imgView = (UIImageView *)[self.view viewWithTag:200];
        imgView.hidden = YES;
        _nextShowTag = 201;
    }
    
    if (!_timer)
    {
        tmpInt = 0;
        
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(startLottaryAnimation) userInfo:nil repeats:YES];
    }
}

- (void)startLottaryAnimation
{
    if (tmpInt == _rewordInt)
    {
        _startBtn.userInteractionEnabled = YES;
        _goBackBtn.userInteractionEnabled = YES;

        if (_timer)
        {
            [_timer invalidate];
            _timer = nil;
        }
        
        NSDictionary *dict = [NSDictionary dictionaryWithDictionary:[PassValueClass sharedIntance].lottoryResultDict];
        NSString *type   = [dict objectForKey:kRewordType];
        NSString *index  = [dict objectForKey:kRewordIndex];
        NSString *idName = [dict objectForKey:kRewordId];

        if ([type integerValue] == 0)
        {
            UIAlertView *noRewordAlert = [[UIAlertView alloc] initWithTitle:@"不好意思,这次没有抽中,请再接再厉!"
                                                                    message:nil
                                                                   delegate:self
                                                          cancelButtonTitle:@"知道了"
                                                          otherButtonTitles:@"再次抽奖", nil];
            noRewordAlert.tag = kUserLottoryAgain;
            [noRewordAlert show];
            int i = [_scoreLbl.text intValue] - 10;
            _scoreLbl.text = [NSString stringWithFormat:@"%d",i];
            
        }
        else
        {
            //先验证抽奖
            [self verifyThisLottory:[index intValue] requestID:idName];
        }
    }
    else
    {
        if (tmpInt < 7)
        {
            _nextShowTag = 200 + tmpInt + 1;
        }
        else if (7 <= tmpInt && tmpInt < 15)
        {
            _nextShowTag = 200 + tmpInt - 7;
        }
        else if(tmpInt >= 15)
        {
            _nextShowTag = 200 + tmpInt - 15;
        }
        tmpInt ++;
        [self loadLottaryView:_nextShowTag];
    }
}


- (void)initialLottoryView//初始化抽奖页面
{
    currentCoverInt = 1;
    for (int i = 0; i < 8; i++)
    {
        int tagInt = 200 + i;
        UIImageView *imvView = (UIImageView *)[self.view viewWithTag:tagInt];
        if (imvView.tag == 200)
        {
            imvView.hidden = YES;
        }
        else
        {
            imvView.hidden = NO;
        }
    }
}


- (void)loadLottaryView:(NSInteger)nestShowImgTag//抽奖动画
{
    for (int i = 0; i < 8; i++)
    {
        int tagInt = 200 + i;
        UIImageView *imvView = (UIImageView *)[self.view viewWithTag:tagInt];
        if (imvView.tag == nestShowImgTag)
        {
            imvView.hidden = YES;
        }
        else
        {
            imvView.hidden = NO;
        }
    }
}

#pragma mark - 加载中奖信息

- (void)verifyThisLottory:(NSInteger)index requestID:(NSString *)requestid
{
    NSString *string    = [RequestCMD requestCMD:kConfirmLottary];//验证抽奖
    NSMutableData *data = [RequestCMD getWantedData:string];
    [[SocketObject sharedInstance].gcdSocket writeData:data withTimeout:-1 tag:kConfirmLottary];//1076---验证中奖信息
}

- (void)getLottaryConfirm
{
    NSString *scoreStr = [PassValueClass sharedIntance].scoreStr;
    _scoreLbl.text = scoreStr;

    NSString *confirmStr = [PassValueClass sharedIntance].confirmResult;
    
    if ([confirmStr integerValue] == 1)
    {
        _detailView.hidden = NO;
        [self loadRewordData];//加载获奖信息
    }
    else
    {
        UIAlertView *confirmLottoryFailedAlert = [[UIAlertView alloc] initWithTitle:@"网络验证失败,请重试" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"知道了", nil];
        [confirmLottoryFailedAlert show];
    }
}

- (void)loadRewordData
{
    NSDictionary *dict = [NSDictionary dictionaryWithDictionary:[PassValueClass sharedIntance].lottoryResultDict];
    NSString *index  = [dict objectForKey:kRewordIndex];
    
    NSArray *array = [NSArray arrayWithArray:[PassValueClass sharedIntance].rewordArray];
    NSDictionary *tmpDict = [array objectAtIndex:[index integerValue] - 1];
    NSString *str      = [tmpDict objectForKey:kRewordUrl];
    NSString *nameStr  = [tmpDict objectForKey:kRewordName];
    
    _rewordImgView.imageURL = [NSURL URLWithString:str];
    _rewordLbl.text = nameStr;
}

- (IBAction)hideRewordView//隐藏抽奖界面
{
    _detailView.hidden = YES;
}

#pragma mark - 关于界面

- (IBAction)showAboutView
{
    _aboutMoreView.hidden = NO;
}

- (IBAction)hideAboutView
{
    _aboutMoreView.hidden = YES;
}
@end
